﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using VirtuosoDal.Config;

namespace VirtuosoDal
{
   public static class EventsConfigManager
   {
      private static XDocument _xDocument;

      //ToDo: This implementation doesn't care about derived event categories and types. Currently
      //      they don't have additional properties, but it should be implemented
      public static bool TryGetAdditionalProperties(string uri, out List<string> properties)
      {
         if (_xDocument == null)
         {
            string eventsFilePath = ConfigurationManager.AppSettings["EventsFilePath"];
            if (String.IsNullOrEmpty(eventsFilePath))
               throw new Exception("EventsFilePath setting should be set in config's AppSettings section");

            _xDocument = XDocument.Load(eventsFilePath);
         }

         properties = new List<string>();

         IEnumerable<XElement> elements = _xDocument.Root.Elements();
         foreach (var entityElement in elements)
         {
            string currentEventUri = entityElement.Attribute("Uri").Value;
            if (currentEventUri == uri)
            {
               XElement propertiesElement = entityElement.Elements().Where(e => e.Name == "Properties").FirstOrDefault();
               if (propertiesElement != null)
                  properties.AddRange(propertiesElement.Elements().Select(propertyElement => propertyElement.Attribute("Uri").Value));

               return true;
            }
         }

         return false;
      }
   }
}
